import echarts from './echartsPlugin';

/** 创建echarts实例
 * @param domRef 挂载echarts的虚拟dom节点
 * @param autoResize 自动resize
 */
export function useEcharts(domRef: Ref<HTMLDivElement | undefined>, autoResize = false) {
	let echartsIns: echarts.ECharts | null = null;

	/** 初始化 */
	function init() {
		if (echartsIns) {
			dispose();
		}
		if (unref(domRef)) {
			echartsIns = echarts.init(unref(domRef) as HTMLDivElement);
			if (autoResize) {
				autoResizeFn();
			}
		}
	}
	onMounted(() => {
		nextTick(() => {
			init();
		});
	});

	/** echarts resize */
	function resize() {
		setTimeout(() => {
			echartsIns && echartsIns.resize();
		}, 0);
	}

	/** 自动resize */
	function autoResizeFn() {
		window.addEventListener('resize', resize);
	}

	/** 重绘数据 */
	function setOption(option) {
		echartsIns && echartsIns.setOption(option);
	}

	/** 清除后重绘数据 */
	function resetOption(option) {
		echartsIns && echartsIns.clear();
		echartsIns && echartsIns.setOption(option);
	}

	/** 销毁 */
	function dispose() {
		echartsIns && echartsIns.dispose();
		window.removeEventListener('resize', resize);
		echartsIns = null;
	}

	onBeforeUnmount(() => {
		dispose();
	});

	return {
		init,
		echartsIns,
		resize,
		setOption,
		resetOption,
	};
}
